package com.taglab.chic.taglib.adwords;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

/**
 * Google AdWords tag useful for adding tracking to a page.
 *
 * Recommend putting this as the last tag before &lt;/body&gt;.
 *
 * Currently only supports the hidden version, i.e. it will not present a button or icon to the end-user.
 *
 * @author Peter O'Shaughnessy
 */
public class GoogleAdwordsTag extends TagSupport {

  private static final long serialVersionUID = 3416277670012147656L;

  private String conversionId;
  private String conversionLabel;

  public void setConversionId(String conversionId) {
    this.conversionId = conversionId;
  }
  
  public void setConversionLabel(String conversionLabel) {
    this.conversionLabel = conversionLabel;
  }
  
  @Override
  public int doStartTag() throws JspException {
    
    if( conversionId == null )
      throw new IllegalStateException("Conversion ID not set");
    else if( conversionLabel == null )
      throw new IllegalStateException("Conversion label not set");

    try {
      JspWriter out = pageContext.getOut();

      out.append("<script language=\"JavaScript\" type=\"text/javascript\">\n");
      out.append("<!--\n");
      out.append("var google_conversion_id = ").append(conversionId).append(";\n");
      out.append("var google_conversion_language = \"en_GB\";\n");
      out.append("var google_conversion_format = \"3\";\n");
      out.append("var google_conversion_color = \"ffffff\";\n");
      out.append("var google_conversion_label = \"").append(conversionLabel).append("\";\n");
      out.append("//-->\n");
      out.append("</script>\n");
      out.append("<script language=\"JavaScript\" src=\"https://www.googleadservices.com/pagead/conversion.js\">\n");
      out.append("</script>\n");
      out.append("<noscript>\n");
      out.append("<img height=\"1\" width=\"1\" border=\"0\" src=\"https://www.googleadservices.com/pagead/conversion/");
      out.append(conversionId).append("/?label=").append(conversionLabel).append("&amp;guid=ON&amp;script=0\"/>\n");
      out.append("</noscript>\n");

      return EVAL_BODY_INCLUDE;
    } catch (IOException e) {
      throw new JspException(e.toString(), e);
    }
  }
  
}
